﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

namespace FYPHP
{
    public partial class RewardsRedeem : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["fyphp"].ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            SqlCommand cmdSelect;
            SqlDataReader dtrSelect;
            conn.Open();

            cmdSelect = new SqlCommand("SELECT * FROM Reward r, Claim c, Users u WHERE r.r_id=c.r_id AND u.u_id=c.u_id AND c.cl_status='RewardCompleted'", conn);
            dtrSelect = cmdSelect.ExecuteReader();

            ItemList.DataSource = dtrSelect;
            ItemList.DataBind();

            dtrSelect.Close();
            conn.Close();
        }

        protected void ItemList_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "View")
            {
                int tid = Convert.ToInt32(e.CommandArgument.ToString());
                Response.Write("<script> window.open('RewardPrinting.aspx?id="+ tid +"'); </script>");
            }

            else if (e.CommandName == "Complete")
            {
                int tid = Convert.ToInt32(e.CommandArgument.ToString());
                SqlCommand dlt;
                conn.Open();

                dlt = new SqlCommand("UPDATE Claim SET cl_status='RewardShipped' WHERE cl_id=@id", conn);
                dlt.Parameters.AddWithValue("@id", tid);
                dlt.ExecuteNonQuery();

                MessageBox("Redemption completed!");
                Redirect("RewardsRedeem.aspx");
            }
        }

        private void MessageBox(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }

        private void Redirect(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language=\"javascript\">window.location='" + msg + "';</script>";
            Page.Controls.Add(lbl);
        }
    }
}